package com.yiwenup.struct._03_collect.map;

import com.yiwenup.struct._03_collect.map.base.Map;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.Objects;
import java.util.Queue;

/**
 * 红黑树实现
 **/
@SuppressWarnings("unchecked")
public class TreeMap<K, V> implements Map<K, V> {
    private int size;
    private Node<K, V> root;
    private Comparator<K> comparator;

    public TreeMap() {
        this(null);
    }

    public TreeMap(Comparator<K> comparator) {
        this.comparator = comparator;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void clear() {
        root = null;
        size = 0;
    }

    @Override
    public V put(K key, V value) {
        keyNotNullCheck(key);

        if (root == null) {
            root = new Node<>(key, value, null);
            size++;
            afterPut(root);
            return null;
        }

        // 找到父节点
        Node<K, V> parent = root;
        Node<K, V> node = root;
        int compare = 0;
        while (node != null) {
            compare = compare(key, node.key);
            parent = node;
            if (compare > 0) {
                node = node.right;
            } else if (compare < 0) {
                node = node.left;
            } else {
                node.key = key;
                V oldValue = node.value;
                node.value = value;
                return oldValue;
            }
        }

        //
        Node<K, V> newNode = new Node<>(key, value, parent);
        if (compare > 0) {
            parent.right = newNode;
        } else {
            parent.left = newNode;
        }
        size++;
        afterPut(newNode);
        return null;
    }

    private void afterPut(Node<K, V> node) {
        Node<K, V> parent = node.parent;
        // 添加的是根节点，或者上溢到了根节点
        if (parent == null) {
            black(node);
            return;
        }

        // 如果父节点是黑色则返回
        if (isBlack(parent)) return;

        // 叔父节点
        Node<K, V> uncle = parent.sibling();
        // 祖父节点
        Node<K, V> grand = parent.parent;
        if (isRed(uncle)) {
            black(parent);
            black(uncle);
            // 将祖父节点当作新添加的节点上溢
            afterPut(red(grand));
            return;
        }

        // 叔父节点不是红色的
        if (parent.isLeftChild()) {
            red(grand);
            if (node.isLeftChild()) {
                // LL
                black(parent);
            } else {
                // LR
                black(node);
                rotateLeft(parent);
            }
            rotateRight(grand);
        } else {
            red(grand);
            if (node.isRightChild()) {
                // RR
                black(parent);
            } else {
                // RL
                black(node);
                rotateRight(parent);
            }
            rotateLeft(grand);
        }
    }

    private void rotateLeft(Node<K, V> g) {
        Node<K, V> p = g.right;
        Node<K, V> t1 = p.left;
        g.right = t1;
        p.left = g;

        afterRotate(g, p, t1);
    }

    private void rotateRight(Node<K, V> g) {
        Node<K, V> p = g.left;
        Node<K, V> t2 = p.right;
        g.left = t2;
        p.right = g;

        afterRotate(g, p, t2);
    }

    private void afterRotate(Node<K, V> g, Node<K, V> p, Node<K, V> t) {
        // 使P成为子树的根节点
        p.parent = g.parent;
        if (g.isLeftChild()) {
            g.parent.left = p;
        } else if (g.isRightChild()) {
            g.parent.right = p;
        } else {
            // g就是整棵树的根节点
            root = p;
        }

        // 使子树的父节点是之前的根节点
        if (t != null) {
            t.parent = g;
        }

        // 使之前根节点的父节点是新的根节点
        g.parent = p;

        // 高度更新
    }

    private boolean isBlack(Node<K, V> node) {
        return colorOf(node) == BLACK;
    }

    private boolean isRed(Node<K, V> node) {
        return colorOf(node) == RED;
    }

    private boolean colorOf(Node<K, V> node) {
        return node == null ? BLACK : node.color;
    }

    private Node<K, V> red(Node<K, V> node) {
        return color(node, RED);
    }

    private Node<K, V> black(Node<K, V> node) {
        return color(node, BLACK);
    }

    /**
     * 染色
     *
     * @param node  染色节点
     * @param color 颜色
     * @return 染色节点
     */
    private Node<K, V> color(Node<K, V> node, boolean color) {
        if (node == null) return null;
        node.color = color;
        return node;
    }

    private void keyNotNullCheck(K key) {
        if (key == null) {
            throw new IllegalArgumentException("key must not be null");
        }
    }

    private int compare(K k1, K k2) {
        if (comparator != null) {
            return comparator.compare(k1, k2);
        }
        return ((Comparable<K>) k1).compareTo(k2);
    }

    @Override
    public V get(K key) {
        Node<K, V> node = node(key);
        return node != null ? node.value : null;
    }

    private Node<K, V> node(K key) {
        Node<K, V> node = this.root;
        while (node != null) {
            int compare = compare(key, node.key);
            if (compare == 0) return node;
            if (compare > 0) {
                node = node.right;
            } else {
                node = node.left;
            }
        }
        return null;
    }

    @Override
    public V remove(K key) {
        return remove(node(key));
    }

    private V remove(Node<K, V> node) {
        if (node == null) return null;

        V oldValue = node.value;

        if (node.hasTwoChildren()) {
            // 度为2
            Node<K, V> successor = successor(node);
            // 后继节点的值覆盖度为2的值
            node.key = successor.key;
            node.value = successor.value;
            // 删除后继节点
            node = successor;
        }

        // 删除度为1或0的节点
        Node<K, V> replace = node.left != null ? node.left : node.right;

        if (replace != null) {
            // 度为1
            replace.parent = node.parent;
            if (node.parent == null) {
                // 度为1，且是根节点
                root = replace;
            } else if (node == node.parent.left) {
                node.parent.left = replace;
            } else {
                node.parent.right = replace;
            }

            afterRemove(replace);
        } else if (node.parent == null) {
            // 度为0，且是根节点
            root = null;
            afterRemove(node);
        } else {
            // 度为0，但不是根节点 -> 叶子节点
            if (node.parent.left == node) {
                node.parent.left = null;
            } else {
                node.parent.right = null;
            }
            afterRemove(node);
        }

        size--;

        return oldValue;
    }

    private void afterRemove(Node<K, V> node) {
        if (isRed(node)) {
            // 如果删除的节点是红色，则直接删除
            // 或者将要取代被删除节点位置的节点，如果是红色
            black(node);
            return;
        }

        // 删除的是叶子
        Node<K, V> parent = node.parent;
        if (parent == null) return;

        // 下溢
        boolean wasLeft = parent.left == null || node.isLeftChild();
        Node<K, V> sibling = wasLeft ? parent.right : parent.left;
        if (wasLeft) {
            // 被删除的节点在左边
            if (isRed(sibling)) {
                // 如果兄弟节点是红色，则通过旋转将情况变成兄弟节点是黑色的情况
                black(sibling);
                red(parent);
                rotateLeft(parent);
                // 重新赋值兄弟
                sibling = parent.right;
            }

            // 兄弟节点是黑色
            if (isBlack(sibling.left) && isBlack(sibling.right)) {
                boolean parentBlack = isBlack(parent);
                black(parent);
                red(sibling);
                if (parentBlack) {
                    afterRemove(parent);
                }
            } else {
                // 兄弟节点至少有一个红色子节点
                if (isBlack(sibling.right)) {
                    rotateRight(sibling);
                    sibling = parent.right;
                }

                color(sibling, colorOf(parent));
                black(sibling.right);
                black(parent);

                rotateLeft(parent);
            }
        } else {
            // 被删除的节点在右边
            if (isRed(sibling)) {
                // 如果兄弟节点是红色，则通过旋转将情况变成兄弟节点是黑色的情况
                black(sibling);
                red(parent);
                rotateRight(parent);
                // 重新赋值兄弟
                sibling = parent.left;
            }

            // 兄弟节点是黑色
            if (isBlack(sibling.left) && isBlack(sibling.right)) {
                boolean parentBlack = isBlack(parent);
                black(parent);
                red(sibling);
                if (parentBlack) {
                    afterRemove(parent);
                }
            } else {
                // 兄弟节点至少有一个红色子节点
                if (isBlack(sibling.left)) {
                    rotateLeft(sibling);
                    sibling = parent.left;
                }

                color(sibling, colorOf(parent));
                black(sibling.left);
                black(parent);

                rotateRight(parent);
            }
        }
    }

    private Node<K, V> successor(Node<K, V> node) {
        if (node == null) return null;

        // 前驱节点在左子树中 node.right.left.left.left....
        Node<K, V> pre = node.right;
        if (pre != null) {
            while (pre.left != null) {
                pre = pre.left;
            }
            return pre;
        }

        // 从父节点中寻找前驱节点
        while (node.parent != null && node == node.parent.right) {
            node = node.parent;
        }

        return node.parent;
    }

    @Override
    public boolean containsKey(K key) {
        return node(key) != null;
    }

    @Override
    public boolean containsValue(V value) {
        if (root == null) return false;
        Queue<Node<K, V>> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            Node<K, V> node = queue.poll();
            if (valEquals(node.value, value)) return true;
            if (node.left != null) queue.offer(node.left);
            if (node.right != null) queue.offer(node.right);
        }

        return false;
    }

    private boolean valEquals(V v1, V v2) {
        return Objects.equals(v1, v2);
    }

    @Override
    public void traversal(Visitor<K, V> visitor) {
        if (visitor == null) return;
        traversal(root, visitor);
    }

    private void traversal(Node<K, V> node, Visitor<K, V> visitor) {
        if (node == null || visitor.stop) return;

        traversal(node.left, visitor);
        if (visitor.stop) return;
        visitor.visit(node.key, node.value);
        traversal(node.right, visitor);
    }

    public static final boolean RED = false;
    public static final boolean BLACK = true;

    private static class Node<K, V> {
        private boolean color = RED;
        private K key;
        private V value;
        private Node<K, V> left;
        private Node<K, V> right;
        private Node<K, V> parent;

        public Node(K key, V value, Node<K, V> parent) {
            this.key = key;
            this.value = value;
            this.parent = parent;
        }

        public boolean isLeaf() {
            return left == null && right == null;
        }

        public boolean hasTwoChildren() {
            return left != null && right != null;
        }

        public boolean isLeftChild() {
            return parent != null && this == parent.left;
        }

        public boolean isRightChild() {
            return parent != null && this == parent.right;
        }

        public Node<K, V> sibling() {
            if (isLeftChild()) {
                return parent.right;
            }
            if (isRightChild()) {
                return parent.left;
            }
            return null;
        }
    }
}
